#include <iostm8s103f3.h>
#include <intrinsics.h>

unsigned long int TimerCnt = 0;
unsigned long int TargetCnt = 62500;
unsigned char LED = 0;

int main( void )
{
  // setup clock
  CLK_CKDIVR &= (unsigned char)(~0x18);  // 16MHz high speed internal clock
  
  //LED: B5
  PB_DDR |= 0x20;  // output
  PB_CR1 |= 0x20;  // push pull
  PB_CR2 |= 0x20;  // 10MHz output speed
  
  // setup timer 2; generate a 125KHz(8us) interrupt
  TIM2_PSCR = 0x07;   // prescaler = 128; 16MHz/128=125KHz
  TIM2_ARRH = 0x00;   // high byte of 1
  TIM2_ARRL = 0x01;   // low byte of 1
  TIM2_IER = 0x01;    // update interrupts enabled
  TIM2_CR1 = 0x01;    // enable the timer
  
  // enable interrupt
  __enable_interrupt();
  
  while (1) {
    //TargetCnt++;
  }
}


//  Timer 2 Overflow handler.
#pragma vector = TIM2_OVR_UIF_vector
__interrupt void TIM2_OVR_UIF_IRQHandler(void)
{
  TimerCnt++;
  if (TimerCnt >= TargetCnt) {
    TimerCnt = 0;
    if (LED == 0) {
      LED = 1;
      PB_ODR &= 0xDF;  // LOW is ON
    }
    else {
      LED = 0;
      PB_ODR |= 0x20;  // HIGH if OFF
    }
  }
  TIM2_SR1 &= 0xFE;
}
